#!/bin/bash

set -e

RUST_DIR=$1
BASE=$2
UPDATED=$3

SCRIPT_DIR=$(dirname "$0")
VERUS_DIR=$(realpath $SCRIPT_DIR/../..)

VERUS_TMP_DIR=$(mktemp -d)
echo $VERUS_TMP_DIR

cd $VERUS_DIR
GIT_CONFIG_USER_NAME=$(git config user.name)
GIT_CONFIG_USER_EMAIL=$(git config user.email)

cd $VERUS_TMP_DIR
git init

cd $RUST_DIR
git checkout $BASE
GIT_BASE_HASH=$(git rev-parse HEAD)

cd $VERUS_TMP_DIR
mkdir source
mkdir source/rustc_hir_typeck
mkdir source/rustc_hir_typeck/src
cp -r $RUST_DIR/compiler/rustc_mir_build $VERUS_TMP_DIR/source/
cp -r $RUST_DIR/compiler/rustc_hir_typeck/src/upvar.rs $VERUS_TMP_DIR/source/rustc_hir_typeck/src/
cp -r $RUST_DIR/compiler/rustc_hir_typeck/src/expr_use_visitor.rs $VERUS_TMP_DIR/source/rustc_hir_typeck/src/
git add source
git commit --author="nobody <nobody>" -m "base (from $BASE)" 

cd $RUST_DIR
git checkout $UPDATED
GIT_UPDATED_HASH=$(git rev-parse HEAD)

cd $VERUS_TMP_DIR
git rm -r source
mkdir source
mkdir source/rustc_hir_typeck
mkdir source/rustc_hir_typeck/src
cp -r $RUST_DIR/compiler/rustc_mir_build $VERUS_TMP_DIR/source/
cp -r $RUST_DIR/compiler/rustc_hir_typeck/src/upvar.rs $VERUS_TMP_DIR/source/rustc_hir_typeck/src/
cp -r $RUST_DIR/compiler/rustc_hir_typeck/src/expr_use_visitor.rs $VERUS_TMP_DIR/source/rustc_hir_typeck/src/
git add source
git commit --author="nobody <nobody>" -m "Updating forked Rust code: from $BASE ($GIT_BASE_HASH) to $UPDATED ($GIT_UPDATED_HASH)" -m "Diff generated by: update-rustc-forks.sh" -m "Applied by: $GIT_CONFIG_USER_NAME <$GIT_CONFIG_USER_EMAIL>"

GIT_COMMIT=$(git rev-parse HEAD)

cd $VERUS_DIR
git fetch $VERUS_TMP_DIR/.git

echo ""
echo "===="
echo ""

echo "Diff prepared. When you're ready to apply it, run:"
echo "git cherry-pick $GIT_COMMIT"

